<template>
  <div class="order-manage">
    <el-card>
      <div class="card-header">
        <h2>订单管理</h2>
        <div class="filter-group">
          <el-select
              v-model="filterStatus"
              placeholder="请选择订单状态"
              style="width: 160px; margin-right: 10px"
          >
            <el-option label="全部" value="" />
            <el-option label="准备中" value="1" />
            <el-option label="已上菜" value="2" />
            <el-option label="待付款" value="3" />
            <el-option label="已付款" value="4" />
            <el-option label="退款" value="5" />
          </el-select>
          <el-input
              v-model="filterTableNumber"
              placeholder="请输入桌号"
              style="width: 160px; margin-right: 10px"
              clearable
          />
          <el-button type="primary" @click="handleFilter">筛选</el-button>
        </div>
      </div>

      <!-- 订单列表 -->
      <el-table
          :data="orderList"
          border
          style="width: 100%"
          row-key="id"
      >
        <el-table-column prop="id" label="订单ID" width="100" />
        <el-table-column prop="number" label="订单号" />
        <el-table-column prop="tableNumber" label="桌号" />
        <el-table-column prop="userName" label="用户" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="orderTime" label="下单时间" width="180">
          <template #default="scope">
            {{ $filters.formatDateTime(scope.row.orderTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="scope">
            <el-tag
                :type="getStatusTagType(scope.row.status)"
            >
              {{ getStatusDesc(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payStatus" label="支付状态" width="120">
          <template #default="scope">
            <el-tag
                :type="getPayStatusTagType(scope.row.payStatus)"
            >
              {{ getPayStatusDesc(scope.row.payStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row.id)"
            >
              查看详情
            </el-button>
            <el-button
                type="warning"
                size="small"
                @click="handleCancelOrder(scope.row.id)"
                :disabled="!canCancel(scope.row.status)"
            >
              取消订单
            </el-button>
            <el-button
                type="success"
                size="small"
                @click="handleUpdateStatus(scope.row.id)"
                :disabled="!canUpdateStatus(scope.row.status)"
            >
              更新状态
            </el-button>
            <el-button
                type="info"
                size="small"
                @click="handleUpdatePayStatus(scope.row.id)"
                :disabled="!canUpdatePayStatus(scope.row.payStatus)"
            >
              更新支付状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination" style="margin-top: 15px; text-align: right;">
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElTag } from 'element-plus';
import {
  getOrderPage,
  cancelOrder,
  updateOrderStatus,
  updatePayStatus
} from '../api/order';

// 表格数据
const orderList = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const filterStatus = ref('');
const filterTableNumber = ref('');

// 加载订单列表
const loadOrderList = async () => {
  try {
    const response = await getOrderPage({
      page: page.value,
      pageSize: pageSize.value,
      status: filterStatus.value,
      tableNumber: filterTableNumber.value
    });
    if (response.code === 200) {
      orderList.value = response.data.records;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('加载订单失败:', error);
    ElMessage.error('获取订单列表失败');
  }
};

// 筛选
const handleFilter = () => {
  page.value = 1;
  loadOrderList();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadOrderList();
};

const handleCurrentChange = (val) => {
  page.value = val;
  loadOrderList();
};

// 订单状态描述
const getStatusDesc = (status) => {
  switch (status) {
    case 1: return '准备中';
    case 2: return '已上菜';
    case 3: return '待付款';
    case 4: return '已付款';
    case 5: return '退款';
    default: return '未知状态';
  }
};

// 订单状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 1: return 'info';
    case 2: return 'success';
    case 3: return 'warning';
    case 4: return 'success';
    case 5: return 'danger';
    default: return 'default';
  }
};

// 支付状态描述
const getPayStatusDesc = (payStatus) => {
  switch (payStatus) {
    case 0: return '未支付';
    case 1: return '已支付';
    case 2: return '退款';
    default: return '未知状态';
  }
};

// 支付状态标签类型
const getPayStatusTagType = (payStatus) => {
  switch (payStatus) {
    case 0: return 'warning';
    case 1: return 'success';
    case 2: return 'danger';
    default: return 'default';
  }
};

// 是否可取消订单（仅准备中、待付款可取消）
const canCancel = (status) => {
  return status === 1 || status === 3;
};

// 是否可更新订单状态（排除已完成/退款状态）
const canUpdateStatus = (status) => {
  return status !== 4 && status !== 5;
};

// 是否可更新支付状态（未支付、已支付可更新）
const canUpdatePayStatus = (payStatus) => {
  return payStatus === 0 || payStatus === 1;
};

// 取消订单
const handleCancelOrder = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '取消确认', {
      type: 'warning'
    });

    const response = await cancelOrder(id);
    if (response.code === 200) {
      ElMessage.success('订单取消成功');
      loadOrderList();
    } else {
      ElMessage.error(response.msg || '取消失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error);
      ElMessage.error('取消订单操作失败');
    }
  }
};

// 更新订单状态
const handleUpdateStatus = async (id) => {
  const statusOptions = [
    { label: '准备中', value: 1 },
    { label: '已上菜', value: 2 },
    { label: '待付款', value: 3 },
    { label: '已付款', value: 4 },
    { label: '退款', value: 5 }
  ];

  try {
    const { value } = await ElMessageBox.prompt('请选择目标状态', '更新订单状态', {
      inputType: 'select',
      inputOptions: statusOptions,
      inputValue: '2' // 默认选中已上菜
    });

    const response = await updateOrderStatus(id, value);
    if (response.code === 200) {
      ElMessage.success(response.msg || '状态更新成功');
      loadOrderList();
    } else {
      ElMessage.error(response.msg || '状态更新失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新状态失败:', error);
      ElMessage.error('更新状态操作失败');
    }
  }
};

// 更新支付状态
const handleUpdatePayStatus = async (id) => {
  const payStatusOptions = [
    { label: '未支付', value: 0 },
    { label: '已支付', value: 1 },
    { label: '退款', value: 2 }
  ];

  try {
    const { value } = await ElMessageBox.prompt('请选择支付状态', '更新支付状态', {
      inputType: 'select',
      inputOptions: payStatusOptions,
      inputValue: '1' // 默认选中已支付
    });

    const response = await updatePayStatus(id, value);
    if (response.code === 200) {
      ElMessage.success(response.msg || '支付状态更新成功');
      loadOrderList();
    } else {
      ElMessage.error(response.msg || '支付状态更新失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新支付状态失败:', error);
      ElMessage.error('更新支付状态操作失败');
    }
  }
};

// 查看订单详情（可扩展，此处仅示例）
const handleViewDetail = (id) => {
  ElMessage.info(`查看订单ID为${id}的详情`);
  // 可跳转到详情页：router.push({ path: '/order/detail', query: { id } });
};

// 页面初始化
onMounted(() => {
  loadOrderList();
});
</script>

<style scoped>
.order-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  gap: 10px;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}
</style>